package com.jeespring.order.service.impl;

import com.jeespring.dto.BusinessDTO;
import com.jeespring.dto.ResponseDTO;
import com.jeespring.entity.Account;
import com.jeespring.entity.Order;
import com.jeespring.order.dao.OrderDao;
import com.jeespring.service.AccountService;
import com.jeespring.service.OrderService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

/**
 * @Title: OrderServiceImpl
 * @Description:
 * @Author 张朝阳
 * @Date 2020/11/29 15:38
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Reference
    private AccountService accountService;

    @Override
    public List<Order> query(Order order) {
        return orderDao.select(order);
    }

    @Override
    public ResponseDTO<Order> createOrder(BusinessDTO businessDTO) {
        log.info("全局事务id ：" + RootContext.getXID());

        ResponseDTO<Order> response = new ResponseDTO<>();
        //扣减用户账户
        Account account = new Account();
        account.setUserId(businessDTO.getUserId());
        account.setAmount(businessDTO.getAmount());
        response = accountService.decreaseAccount(account);

        // 异常发生
        if (businessDTO.getFlag() == 2){
            int i = 10/0;
        }

        //生成订单
        Order order = new Order();
        //生成订单号
        order.setOrderNo(String.valueOf(System.currentTimeMillis()));
        order.setUserId(businessDTO.getUserId());
        order.setCommodityCode(businessDTO.getCommodityCode());
        order.setCount(businessDTO.getCount());
        order.setAmount(businessDTO.getAmount());
        try {
            orderDao.createOrder(order);
        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("创建订单失败！");
            return response;
        }

        if (!response.isSuccess()) {
            response.setSuccess(false);
            response.setMessage("扣减账号金额失败！");
            return response;
        }

        response.setMessage("创建订单成功！");
        return response;
    }
}
